package com.wntms.auser.service.impl;

import com.wntms.auser.dao.UserDao;
import com.wntms.auser.pojo.User;
import com.wntms.auser.service.UserService;
import com.wntms.auser.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 注册
     * @param username
     * @return
     */
    @Override
    public String login(User user) {

        //代码编写，能够调用到
        Authentication authentication = new UsernamePasswordAuthenticationToken(user.getAccount(), user.getPassword());
        authenticationManager.authenticate(authentication);
        /*
        authenticate底层会使用PasswordEncode.matches(UsernamePasswordAuthenticationToken中的密码，UserDetailsImpl中的密码)
        如果校验成功不报错，校验失败会报错，底层向错误捕获响应回403
         */
        Map<String, String> map = new HashMap<>();
        map.put("account", user.getAccount());
        return JwtUtils.getToken(map);

    }

    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public boolean register(User user) {
        int i = userDao.insertUser(user);
        if (i != 0) {
           return true;
        }
        return false;
    }

    /**
     * 判断用户名是否重复
     * @param username
     * @return
     */
    @Override
    public boolean inspectUsername(String username) {
        User user1 = userDao.findByUserName(username);
        if (user1 == null) {
            return true;
        }
        return false;
    }
}
